{% extends 'base.html' %}
{% load static %}

{% block title %}日志管理{% endblock %}

{% block content %}
<div class="row">
    <!-- 侧边栏（保持不变） -->
    <div class="col-md-3 col-lg-2 sidebar p-3">
        <div class="list-group">
            <a href="{% url 'dashboard' %}" class="list-group-item list-group-item-action" data-target="content-dashboard">仪表盘</a>
            <a href="{% url 'user_manage' %}" class="list-group-item list-group-item-action">用户管理</a>
            <a href="{% url 'content_manage' %}" class="list-group-item list-group-item-action">内容管理</a>
            <a href="{% url 'system_config' %}" class="list-group-item list-group-item-action">系统配置</a>
            <a href="{% url 'data_statistics' %}" class="list-group-item list-group-item-action">数据统计</a>
            <a href="{% url 'log_manage' %}" class="list-group-item list-group-item-action active">日志管理</a>
            <a href="{% url 'message_center' %}" class="list-group-item list-group-item-action">消息中心</a>
            <a href="{% url 'help_document' %}" class="list-group-item list-group-item-action">帮助文档</a>
        </div>
    </div>

    <!-- 内容区域 -->
    <div class="col-md-9 col-lg-10 p-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h3 class="text-xl font-bold text-gray-800">系统日志管理</h3>
            <div class="flex space-x-2">
                <button id="export-logs" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all flex items-center">
                    <i class="fa fa-download mr-2"></i> 导出日志
                </button>
            </div>
        </div>

        <!-- 筛选区域 -->
        <div class="bg-white rounded-lg shadow-sm p-4 mb-4">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div class="relative">
                    <input type="text" id="log-search" placeholder="搜索关键词..."
                           class="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none transition-all w-full">
                    <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                </div>
                <select id="log-level-filter" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none">
                    <option value="">所有级别</option>
                    <option value="info">信息</option>
                    <option value="warning">警告</option>
                    <option value="error">错误</option>
                    <option value="critical">严重</option>
                </select>
                <select id="operation-type-filter" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none">
                    <option value="">所有操作</option>
                    <option value="login">登录</option>
                    <option value="logout">登出</option>
                    <option value="create">创建</option>
                    <option value="update">更新</option>
                    <option value="delete">删除</option>
                    <option value="upload">上传</option>
                    <option value="download">下载</option>
                </select>
                <div class="grid grid-cols-2 gap-2">
                    <div class="relative">
                        <input type="date" id="start-date" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none w-full">
                        <i class="fa fa-calendar absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>
                    <div class="relative">
                        <input type="date" id="end-date" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none w-full">
                        <i class="fa fa-calendar absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>
                </div>
            </div>
            <div class="mt-4 flex justify-end">
                <button id="apply-filters" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all flex items-center">
                    <i class="fa fa-filter mr-2"></i> 应用筛选
                </button>
                <button id="reset-filters" class="ml-2 bg-gray-200 hover:bg-gray-300 text-gray-700 px-4 py-2 rounded-lg transition-all">
                    重置
                </button>
            </div>
        </div>

        <!-- 日志表格 -->
        <div class="bg-white rounded-lg shadow-sm overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="w-10 px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                <input type="checkbox" id="select-all-logs" class="rounded text-primary focus:ring-primary/50">
                            </th>
                            <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer" data-sort="timestamp">
                                时间 <i class="fa fa-sort ml-1 text-gray-400"></i>
                            </th>
                            <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer" data-sort="level">
                                级别 <i class="fa fa-sort ml-1 text-gray-400"></i>
                            </th>
                            <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer" data-sort="user">
                                用户 <i class="fa fa-sort ml-1 text-gray-400"></i>
                            </th>
                            <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer" data-sort="operation">
                                操作类型 <i class="fa fa-sort ml-1 text-gray-400"></i>
                            </th>
                            <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                操作描述
                            </th>
                            <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer" data-sort="ip">
                                IP地址 <i class="fa fa-sort ml-1 text-gray-400"></i>
                            </th>
                            <th scope="col" class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                操作
                            </th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200" id="log-table-body">
                        <!-- 日志数据将由JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
            <!-- 分页 -->
            <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
                <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                    <div>
                        <p class="text-sm text-gray-700">
                            显示第 <span class="font-medium" id="start-count">1</span> 至 <span class="font-medium" id="end-count">10</span> 条，共 <span class="font-medium" id="total-count">256</span> 条结果
                        </p>
                    </div>
                    <div>
                        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                            <a href="#" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                                <span class="sr-only">第一页</span>
                                <i class="fa fa-angle-double-left"></i>
                            </a>
                            <a href="#" class="relative inline-flex items-center px-2 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                                <span class="sr-only">上一页</span>
                                <i class="fa fa-angle-left"></i>
                            </a>
                            <a href="#" aria-current="page" class="z-10 bg-primary text-white relative inline-flex items-center px-4 py-2 border border-primary text-sm font-medium">
                                1
                            </a>
                            <a href="#" class="bg-white border-gray-300 text-gray-500 hover:bg-gray-50 relative inline-flex items-center px-4 py-2 border text-sm font-medium">
                                2
                            </a>
                            <a href="#" class="bg-white border-gray-300 text-gray-500 hover:bg-gray-50 relative inline-flex items-center px-4 py-2 border text-sm font-medium">
                                3
                            </a>
                            <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700">
                                ...
                            </span>
                            <a href="#" class="bg-white border-gray-300 text-gray-500 hover:bg-gray-50 relative inline-flex items-center px-4 py-2 border text-sm font-medium">
                                26
                            </a>
                            <a href="#" class="relative inline-flex items-center px-2 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                                <span class="sr-only">下一页</span>
                                <i class="fa fa-angle-right"></i>
                            </a>
                            <a href="#" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                                <span class="sr-only">最后一页</span>
                                <i class="fa fa-angle-double-right"></i>
                            </a>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 日志详情模态框 -->
<div id="log-detail-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 overflow-hidden transform transition-all max-h-[90vh] flex flex-col">
        <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
            <h3 class="text-lg font-medium text-gray-900">日志详情</h3>
            <button id="close-modal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="px-6 py-4 overflow-y-auto" id="modal-content">
            <!-- 日志详情内容将由JavaScript动态生成 -->
        </div>
        <div class="px-6 py-4 bg-gray-50 flex justify-end">
            <button id="close-detail" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                关闭
            </button>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 模拟日志数据
    const logData = [
        {
            id: 1,
            timestamp: '2024-06-01 08:30:45',
            level: 'info',
            user: 'admin',
            operation: 'login',
            description: '用户 admin 登录系统',
            ip: '192.168.1.100',
            details: {
                user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
                session_id: '1234567890abcdef',
                login_time: '2024-06-01 08:30:45',
                location: '北京市'
            }
        },
        {
            id: 2,
            timestamp: '2024-06-01 09:15:22',
            level: 'warning',
            user: 'editor',
            operation: 'update',
            description: '尝试更新不存在的内容 (ID: 9999)',
            ip: '192.168.1.101',
            details: {
                user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
                operation_time: '2024-06-01 09:15:22',
                error_message: 'Content with ID 9999 does not exist'
            }
        },
        {
            id: 3,
            timestamp: '2024-06-01 10:02:17',
            level: 'info',
            user: 'user1',
            operation: 'create',
            description: '创建新文章《如何使用系统功能》',
            ip: '192.168.1.102',
            details: {
                user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
                operation_time: '2024-06-01 10:02:17',
                content_id: 1234,
                title: '如何使用系统功能'
            }
        },
        {
            id: 4,
            timestamp: '2024-06-01 11:45:33',
            level: 'error',
            user: 'system',
            operation: 'database',
            description: '数据库连接超时',
            ip: '127.0.0.1',
            details: {
                error_time: '2024-06-01 11:45:33',
                error_code: '500',
                error_message: 'Database connection timeout after 30 seconds',
                stack_trace: 'Traceback (most recent call last):\n  File "/app/db.py", line 45, in connect\n    conn = psycopg2.connect(...)\n  psycopg2.OperationalError: connection timeout expired'
            }
        },
        {
            id: 5,
            timestamp: '2024-06-01 13:20:05',
            level: 'info',
            user: 'admin',
            operation: 'delete',
            description: '删除过期用户会话 (ID: 5678)',
            ip: '192.168.1.100',
            details: {
                user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
                operation_time: '2024-06-01 13:20:05',
                session_id: '5678abcdef1234'
            }
        },
        {
            id: 6,
            timestamp: '2024-06-01 14:08:19',
            level: 'info',
            user: 'user2',
            operation: 'upload',
            description: '上传文件 "documentation.pdf"',
            ip: '192.168.1.103',
            details: {
                user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/114.0.1823.51 Safari/537.36',
                operation_time: '2024-06-01 14:08:19',
                file_name: 'documentation.pdf',
                file_size: '2.4 MB',
                file_type: 'application/pdf'
            }
        },
        {
            id: 7,
            timestamp: '2024-06-01 15:30:47',
            level: 'critical',
            user: 'system',
            operation: 'server',
            description: '服务器内存使用率达到95%',
            ip: '127.0.0.1',
            details: {
                error_time: '2024-06-01 15:30:47',
                current_usage: '95%',
                threshold: '85%',
                process_list: 'nginx, python, postgres'
            }
        },
        {
            id: 8,
            timestamp: '2024-06-01 16:15:52',
            level: 'info',
            user: 'editor',
            operation: 'publish',
            description: '发布文章《新技术趋势分析》',
            ip: '192.168.1.101',
            details: {
                user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
                operation_time: '2024-06-01 16:15:52',
                content_id: 1235,
                title: '新技术趋势分析'
            }
        },
        {
            id: 9,
            timestamp: '2024-06-01 17:45:11',
            level: 'warning',
            user: 'user3',
            operation: 'download',
            description: '尝试下载不存在的文件 (ID: 4321)',
            ip: '192.168.1.104',
            details: {
                user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Firefox/114.0',
                operation_time: '2024-06-01 17:45:11',
                error_message: 'File with ID 4321 does not exist'
            }
        },
        {
            id: 10,
            timestamp: '2024-06-01 18:20:33',
            level: 'info',
            user: 'admin',
            operation: 'logout',
            description: '用户 admin 登出系统',
            ip: '192.168.1.100',
            details: {
                user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
                session_id: '1234567890abcdef',
                logout_time: '2024-06-01 18:20:33'
            }
        }
    ];

    // 渲染日志表格
    function renderLogTable(logs) {
        const tableBody = document.getElementById('log-table-body');
        tableBody.innerHTML = '';

        logs.forEach(log => {
            const row = document.createElement('tr');
            row.className = 'hover:bg-gray-50 transition-colors';
            row.setAttribute('data-id', log.id);

            // 设置日志级别样式
            let levelClass, levelText;
            switch(log.level) {
                case 'info':
                    levelClass = 'bg-blue-100 text-blue-800';
                    levelText = '信息';
                    break;
                case 'warning':
                    levelClass = 'bg-amber-100 text-amber-800';
                    levelText = '警告';
                    break;
                case 'error':
                    levelClass = 'bg-red-100 text-red-800';
                    levelText = '错误';
                    break;
                case 'critical':
                    levelClass = 'bg-rose-100 text-rose-800';
                    levelText = '严重';
                    break;
                default:
                    levelClass = 'bg-gray-100 text-gray-800';
                    levelText = '未知';
            }

            // 设置操作类型文本
            let operationText;
            switch(log.operation) {
                case 'login':
                    operationText = '登录';
                    break;
                case 'logout':
                    operationText = '登出';
                    break;
                case 'create':
                    operationText = '创建';
                    break;
                case 'update':
                    operationText = '更新';
                    break;
                case 'delete':
                    operationText = '删除';
                    break;
                case 'upload':
                    operationText = '上传';
                    break;
                case 'download':
                    operationText = '下载';
                    break;
                case 'publish':
                    operationText = '发布';
                    break;
                case 'database':
                    operationText = '数据库';
                    break;
                case 'server':
                    operationText = '服务器';
                    break;
                default:
                    operationText = log.operation;
            }

            row.innerHTML = `
                <td class="px-4 py-4 whitespace-nowrap">
                    <input type="checkbox" class="log-checkbox rounded text-primary focus:ring-primary/50" data-id="${log.id}">
                </td>
                <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                    ${log.timestamp}
                </td>
                <td class="px-4 py-4 whitespace-nowrap">
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${levelClass}">
                        ${levelText}
                    </span>
                </td>
                <td class="px-4 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    ${log.user}
                </td>
                <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                    ${operationText}
                </td>
                <td class="px-4 py-4 text-sm text-gray-500 max-w-xs truncate">
                    ${log.description}
                </td>
                <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                    ${log.ip}
                </td>
                <td class="px-4 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <a href="#" class="text-indigo-600 hover:text-indigo-900 view-details" data-id="${log.id}">
                        查看详情
                    </a>
                </td>
            `;

            tableBody.appendChild(row);
        });

        // 添加查看详情事件
        document.querySelectorAll('.view-details').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                const logId = parseInt(this.getAttribute('data-id'));
                showLogDetails(logId);
            });
        });
    }

    // 显示日志详情
    function showLogDetails(logId) {
        const log = logData.find(log => log.id === logId);
        if (!log) return;

        const modalContent = document.getElementById('modal-content');
        modalContent.innerHTML = '';

        // 设置日志级别样式
        let levelClass, levelText;
        switch(log.level) {
            case 'info':
                levelClass = 'bg-blue-100 text-blue-800';
                levelText = '信息';
                break;
            case 'warning':
                levelClass = 'bg-amber-100 text-amber-800';
                levelText = '警告';
                break;
            case 'error':
                levelClass = 'bg-red-100 text-red-800';
                levelText = '错误';
                break;
            case 'critical':
                levelClass = 'bg-rose-100 text-rose-800';
                levelText = '严重';
                break;
            default:
                levelClass = 'bg-gray-100 text-gray-800';
                levelText = '未知';
        }

        // 设置操作类型文本
        let operationText;
        switch(log.operation) {
            case 'login':
                operationText = '登录';
                break;
            case 'logout':
                operationText = '登出';
                break;
            case 'create':
                operationText = '创建';
                break;
            case 'update':
                operationText = '更新';
                break;
            case 'delete':
                operationText = '删除';
                break;
            case 'upload':
                operationText = '上传';
                break;
            case 'download':
                operationText = '下载';
                break;
            case 'publish':
                operationText = '发布';
                break;
            case 'database':
                operationText = '数据库';
                break;
            case 'server':
                operationText = '服务器';
                break;
            default:
                operationText = log.operation;
        }

        // 创建详情内容
        const detailsHTML = `
            <div class="mb-4">
                <div class="flex justify-between items-start">
                    <h4 class="text-lg font-semibold text-gray-800">${log.description}</h4>
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${levelClass}">
                        ${levelText}
                    </span>
                </div>
                <div class="mt-1 text-sm text-gray-500">
                    <span class="font-medium">时间:</span> ${log.timestamp} |
                    <span class="font-medium">用户:</span> ${log.user} |
                    <span class="font-medium">操作:</span> ${operationText} |
                    <span class="font-medium">IP:</span> ${log.ip}
                </div>
            </div>

            <div class="border-t border-gray-200 pt-4">
                <h5 class="font-medium text-gray-900 mb-2">详细信息</h5>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    ${Object.entries(log.details).map(([key, value]) => `
                        <div>
                            <dt class="text-sm font-medium text-gray-500">${key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}</dt>
                            <dd class="mt-1 text-sm text-gray-900">
                                ${typeof value === 'object' && value !== null
                                    ? `<pre class="bg-gray-50 p-2 rounded text-xs overflow-x-auto">${JSON.stringify(value, null, 2)}</pre>`
                                    : value}
                            </dd>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;

        modalContent.innerHTML = detailsHTML;

        // 显示模态框
        document.getElementById('log-detail-modal').classList.remove('hidden');
    }

    // 关闭模态框
    document.getElementById('close-modal').addEventListener('click', function() {
        document.getElementById('log-detail-modal').classList.add('hidden');
    });

    document.getElementById('close-detail').addEventListener('click', function() {
        document.getElementById('log-detail-modal').classList.add('hidden');
    });

    // 全选/取消全选
    const selectAllLogs = document.getElementById('select-all-logs');
    const logCheckboxes = document.querySelectorAll('.log-checkbox');

    selectAllLogs.addEventListener('change', function() {
        logCheckboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });

    // 应用筛选
    document.getElementById('apply-filters').addEventListener('click', function() {
        const searchTerm = document.getElementById('log-search').value.toLowerCase();
        const levelFilter = document.getElementById('log-level-filter').value;
        const operationFilter = document.getElementById('operation-type-filter').value;
        const startDate = document.getElementById('start-date').value;
        const endDate = document.getElementById('end-date').value;

        // 过滤日志
        let filteredLogs = logData.filter(log => {
            // 搜索关键词过滤
            if (searchTerm && !log.description.toLowerCase().includes(searchTerm) &&
                !log.user.toLowerCase().includes(searchTerm) &&
                !log.ip.toLowerCase().includes(searchTerm)) {
                return false;
            }

            // 日志级别过滤
            if (levelFilter && log.level !== levelFilter) {
                return false;
            }

            // 操作类型过滤
            if (operationFilter && log.operation !== operationFilter) {
                return false;
            }

            // 日期范围过滤
            if (startDate) {
                const logDate = new Date(log.timestamp.split(' ')[0]);
                const start = new Date(startDate);
                if (logDate < start) {
                    return false;
                }
            }

            if (endDate) {
                const logDate = new Date(log.timestamp.split(' ')[0]);
                const end = new Date(endDate);
                end.setDate(end.getDate() + 1); // 包含当天
                if (logDate >= end) {
                    return false;
                }
            }

            return true;
        });

        // 更新表格
        renderLogTable(filteredLogs);

        // 更新计数
        document.getElementById('total-count').textContent = filteredLogs.length;
        document.getElementById('end-count').textContent = Math.min(10, filteredLogs.length);
    });

    // 重置筛选
    document.getElementById('reset-filters').addEventListener('click', function() {
        document.getElementById('log-search').value = '';
        document.getElementById('log-level-filter').value = '';
        document.getElementById('operation-type-filter').value = '';
        document.getElementById('start-date').value = '';
        document.getElementById('end-date').value = '';

        // 重置表格
        renderLogTable(logData);

        // 重置计数
        document.getElementById('total-count').textContent = logData.length;
    });

    // 导出日志
    document.getElementById('export-logs').addEventListener('click', function() {
        const selectedLogs = Array.from(document.querySelectorAll('.log-checkbox:checked'))
            .map(checkbox => parseInt(checkbox.getAttribute('data-id')));

        let logsToExport;
        if (selectedLogs.length > 0) {
            logsToExport = logData.filter(log => selectedLogs.includes(log.id));
        } else {
            logsToExport = logData;
        }

        if (logsToExport.length === 0) {
            alert('没有可导出的日志');
            return;
        }

        // 实际项目中这里应该发送AJAX请求到后端生成并下载日志文件
        alert(`导出 ${logsToExport.length} 条日志 (模拟操作)`);
    });

    // 排序功能
    const sortHeaders = document.querySelectorAll('th[data-sort]');
    let currentSortField = null;
    let sortDirection = 'asc';

    sortHeaders.forEach(header => {
        header.addEventListener('click', function() {
            const field = this.getAttribute('data-sort');

            // 切换排序方向
            if (currentSortField === field) {
                sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
            } else {
                currentSortField = field;
                sortDirection = 'asc';
            }

            // 更新排序图标
            sortHeaders.forEach(h => {
                const icon = h.querySelector('i');
                if (h === this) {
                    icon.className = `fa fa-sort-${sortDirection} ml-1 text-gray-600`;
                } else {
                    icon.className = `fa fa-sort ml-1 text-gray-400`;
                }
            });

            // 排序日志
            const sortedLogs = [...logData].sort((a, b) => {
                let valueA, valueB;

                switch(field) {
                    case 'timestamp':
                        valueA = new Date(a.timestamp);
                        valueB = new Date(b.timestamp);
                        break;
                    case 'level':
                        valueA = a.level;
                        valueB = b.level;
                        break;
                    case 'user':
                        valueA = a.user.toLowerCase();
                        valueB = b.user.toLowerCase();
                        break;
                    case 'operation':
                        valueA = a.operation.toLowerCase();
                        valueB = b.operation.toLowerCase();
                        break;
                    case 'ip':
                        valueA = a.ip;
                        valueB = b.ip;
                        break;
                    default:
                        return 0;
                }

                if (sortDirection === 'asc') {
                    return valueA < valueB ? -1 : 1;
                } else {
                    return valueA > valueB ? -1 : 1;
                }
            });

            // 更新表格
            renderLogTable(sortedLogs);
        });
    });

    // 初始化页面
    renderLogTable(logData);
});
</script>
{% endblock %}

{% block extra_js %}
<script>
    // 侧边栏交互逻辑
    document.querySelectorAll('.list-group-item').forEach(item => {
        item.addEventListener('click', function(e) {
            document.querySelector('.list-group-item.active').classList.remove('active');
            this.classList.add('active');
        });
    });
</script>
{% endblock %}